package com.dreamlin.gankio

import android.app.Application
import android.content.Context
import android.text.TextUtils
import androidx.lifecycle.ViewModelProvider
import com.scwang.smartrefresh.header.BezierCircleHeader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.footer.BallPulseFooter
import okio.IOException
import java.io.BufferedReader
import java.io.FileReader


class App : Application() {

    init {
        setGlobalRefreshHeaderAndFooter()
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        appContext = this
        application = this
    }

    override fun onCreate() {
        super.onCreate()
        val context = applicationContext
        // 获取当前包名
        val packageName = context.packageName
 /*       // 获取当前进程名
        val processName =
            getProcessName(Process.myPid())
        // 设置是否为上报进程
        val strategy = UserStrategy(context)
        strategy.isUploadProcess = processName == null || processName == packageName
        // 初始化Bugly
        CrashReport.initCrashReport(context, "appId", BuildConfig.DEBUG, strategy)*/
    }

    companion object {
        lateinit var appContext: Context
            private set
        lateinit var application: Application
            private set

        fun getViewModelProvider(): ViewModelProvider.AndroidViewModelFactory {
            return ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        }

        fun setGlobalRefreshHeaderAndFooter() {
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                //指定为经典Header，默认是 贝塞尔雷达Header
                return@setDefaultRefreshHeaderCreator BezierCircleHeader(context)
            }
            SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                //指定为经典Header，默认是 贝塞尔雷达Header
                return@setDefaultRefreshFooterCreator BallPulseFooter(context)
            }
        }

        private fun getProcessName(pid: Int): String? {
            var reader: BufferedReader? = null
            try {
                reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
                var processName: String = reader.readLine()
                if (!TextUtils.isEmpty(processName)) {
                    processName = processName.trim { it <= ' ' }
                }
                return processName
            } catch (throwable: Throwable) {
                throwable.printStackTrace()
            } finally {
                try {
                    reader?.close()
                } catch (exception: IOException) {
                    exception.printStackTrace()
                }
            }
            return null
        }
    }

}
